package com.bailiban.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * @author zhulang
 * @Classname HttpUtil
 * @Description TODO
 * @Date 2020/3/18 23:42
 */
public class HttpUtil {
    public static String getResultData(String url, Map<String, String> params) {
        //    定义最终响应结果
        String resultString = "";
//    创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
//    响应
        CloseableHttpResponse response = null;
        try {


//    创建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
//            遍历参数
                for (String key : params.keySet()) {
                    builder.addParameter(key, params.get(key));
                }
            }
            URI uri = builder.build();
//        创建httpGet请求
            HttpGet httpGet = new HttpGet(uri);
//通过httpClient客户端模拟发送请求
            response = httpClient.execute(httpGet);
//       判断响应是否成功
            if (response.getStatusLine().getStatusCode() == 200) {
//将响应结果转换成字符串
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
